$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'monitor/dashboard/page',
        datatype: "json",
        colModel: [
            { label: '仪表盘ID', name: 'dashboardId', index: "dashboardId", width: 45, key: true, hidden:true },
			{ label: '仪表盘名称', name: 'dashboardName', width: 45, formatter: function(value, options, row){
			    var url = baseURL + "modules/monitor/dashboard/panel/" + row.dashboardId
                    let a = '<a style="cursor:pointer;" onclick="vm.showPanelList('+row.dashboardId + ',\'' + row.dashboardName +'\')">'+value+'</a>';
			    return a;
                }},
			{ label: '创建时间', name: 'createTime', width: 75 },
			{ label: '创建时间', name: 'updateTime', width: 75 }
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.records",
            page: "page.page",
            total: "page.pages",
            records: "page.total"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });

    // layer弹出层中调用vue方法没调通，姑且这样调用吧
    // 添加监控弹出窗：返回
    $(document).on('click','#cancelAddPanel',function(){
        layer.close(vm.addPanelLayerIndex);
    })
    console.info($("#jqGrid"))
});
var vm = new Vue({
    el:'#rrapp',
    data:{
        q:{
            dashboardName: null // 查询条件：渠道名称
        },
        showList: true,
        showPanels: false,
        showPanel: false,
        title:null,
        dashboard:{
            dashboardId: null, // 仪表盘id
            dashboardName: null, // 仪表盘名称
            panels: []
        },
        letterArr: [], // 存放26个小写英文a-z的数组
        // 当前编辑的是dashboard下的哪个panel
        editPanel: {
            targets: [], // 监控变量表达式数组
            formula: '' // 公式

        },
        rule: {
            expression: '', // 根据公式将监控变量组织为promQL
            ruleName: '', // 规则名称
            frequency: '', // 检查频率
            period: '', // 判决周期
            operator: '', // 比较符号
            alertType: '', // 告警类别
            alertLevel: '', // 告警级别
            messageTemplate: '' // 告警消息模板
        }

    },
    mounted() {
        for (let i = 97, j = 0; i < 122; i++, j++) {
            this.letterArr[j] = String.fromCharCode(i);
        }
        this.getOperatorList()
    },
    methods: {
        query: function () {
            vm.reload();
        },
        add: function(){
            vm.showList = false;
            vm.showPanels = false
            vm.showPanel = false
            vm.title = "新增";
            vm.dashboard = {id: null,dashboardName: null}
        },
        // 修改
        update: function () {
            var dashboardId = getSelectedRow();
            if(dashboardId == null){
                return ;
            }
            vm.showList = false;
            vm.showPanels = false
            vm.showPanel = false
            vm.title = "修改";
            vm.getDashboard(dashboardId);
        },
        del: function () {
            var ids = getSelectedRows();
            if(ids == null){
                return ;
            }
            confirm('确定要删除选中的记录？', function(){
                $.ajax({
                    type: "POST",
                    url: baseURL + "monitor/dashboard/remove",
                    contentType: "application/json",
                    data: JSON.stringify(ids),
                    success: function(r){
                        if(r.code == 0){
                            alert('操作成功', function(){
                                vm.reload();
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        saveOrUpdate: function () {
            var url = vm.dashboard.dashboardId == null ? "monitor/dashboard/add" : "monitor/dashboard/update";
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.dashboard),
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(){
                            vm.reload();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        reload: function () {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{
                postData:{'name': vm.q.dashboardName},
                page:page
            }).trigger("reloadGrid");
        },
        // 编辑：根据id获取仪表盘信息
        getDashboard: function(dashboardId){
            $.get(baseURL + "monitor/dashboard/"+ dashboardId, function(r){
                vm.dashboard = r.data;
            });
        },
        // 打开panel界面
        showPanelList: function (dashboardId, dashboardName) {
            vm.showPanels = true
            vm.showList = false
            vm.showPanel = false
            vm.dashboard = {dashboardId: dashboardId, dashboardName:dashboardName};
        },
        // panel界面返回dashboard页面
        returnDashboard: function () {
            vm.reload();
            vm.showPanels = false
            vm.showPanel = false
            vm.showList = true
        },
        // 打开添加panel表单页面
        addPanel: function () {
            vm.editPanel = {
                targets: []
            }
            vm.addExpression();
            vm.showList = false;
            vm.showPanels = false;
            vm.showPanel = true;
        },
        // 添加一个变量
        addExpression: function () {
            let nextLetter = "";
            letter:
                for(let i = 0; i < vm.letterArr.length; i++) {
                    const used = true;
                    used:
                        for (let j = 0; j < vm.editPanel.targets.length; j++) {
                            if (vm.letterArr[i] === vm.editPanel.targets[j].variable) {
                                continue letter;
                            }
                        }
                    nextLetter = vm.letterArr[i];
                    break letter;
                }
            vm.editPanel.targets.push({
                expression: "",
                variable: nextLetter
            })
        },
        // 移除一个指标变量
        removeExpression: function (index) {
            vm.editPanel.targets.splice(index,1);
        },
        getOperatorList: function(){
            $.get(baseURL + "sys/dict/select/operator", function(r){
                console.info(r.data)
            });
        },
        // 取消添加编辑panel，返回panel列表界面
        returnPanels: function () {
            vm.showPanels = true
            vm.showList = false
            vm.showPanel = false
        },
        savePanel: function () {
            console.info(vm.editPanel)
        }
    }
});